package com.zx.dsptuneup_cloud.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.zx.dsptuneup_cloud.Base.BaseActivity;
import com.zx.dsptuneup_cloud.Tools.AsyncTask;
import com.zx.dsptuneup_cloud.Tools.BroadcastUDPVoiceService;
import com.zx.dsptuneup_cloud.Util.ClickUtil;
import com.zx.dsptuneup_cloud.Util.Netty.NettyListener;
import com.zx.dsptuneup_cloud.App;
import com.zx.dsptuneup_cloud.R;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;

import butterknife.BindView;

public class LoginActivity extends BaseActivity implements NettyListener {

    @BindView(R.id.button)
    Button alreadyBtn;

    @BindView(R.id.button2)
    Button manualBtn;
  /*  private Runnable runnable5;
    private Handler handler;*/
    private int connectedTag = 0;
    private final String TAG = "LoginActivity.class";
    private BroadcastUDPVoiceService broadcastUDPVoiceService;
    private BroadcastUDPVoiceService.BroadcastUDPVoiceServiceBinder binder;
    private boolean isBind = false;
    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (BroadcastUDPVoiceService.BroadcastUDPVoiceServiceBinder) service;
            broadcastUDPVoiceService = binder.getService();
            //AsyncTask.getInstance().start();
            broadcastUDPVoiceService.setListener(new BroadcastUDPVoiceService.errorMsgListener() {
                @Override
                public void getErrorMsg(String msg) {
                }
            });

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            broadcastUDPVoiceService = null;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Intent intent = new Intent(this, BroadcastUDPVoiceService.class);
        isBind = bindService(intent,sc,BIND_AUTO_CREATE);
        hideBottomUIMenu();
        dengluBtn_Action();

        int[] b = {0x0, 0x0, 0x0, 0x0};

        float aaa = getFloat(b);
        Log.d("1111", "aaa===" + isBind);


      /*  new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {

                    try {
                        DatagramSocket datagramSocket = new DatagramSocket(5288);
                        byte[] bytes = new byte[1024];
                        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
                        datagramSocket.receive(datagramPacket);
                        String str = new String(datagramPacket.getData(), datagramPacket.getOffset(), datagramPacket.getLength(),"gbk");
                        Log.d(TAG, datagramPacket.getAddress().getHostAddress()+"====="+str);
                        datagramSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }
        }).start();*/

/*
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Intent intent1 = new Intent(LoginActivity.this, HomeActivity.class);
//                        intent.putExtra("TYPE",msg);
        startActivity(intent1);
        finish();*/
//        String hexStr = ByteToString.bytesToHexString(b);
//        String aa = NumberBaseConversionUtil.sixToDecimalTen(hexStr);
//        Log.e("1111","aa==="+aa);

////                double f = 0.83079689;
//        double f = -1.77781188488;
//        String str = NumberBaseConversionUtil.tenDecimalToSixTeen(f);
//        Log.e(TAG, "getHexadecimal====="+str);
////
//        String aa = "f8000000";
//        String value = NumberBaseConversionUtil.sixToDecimalTen(aa);
    }

    /**
     * int数组直接转float
     */
    public static float getFloat(int[] b) {
        int accum = 0;
        accum = accum | (b[0] & 0xff) << 0;
        accum = accum | (b[1] & 0xff) << 8;
        accum = accum | (b[2] & 0xff) << 16;
        accum = accum | (b[3] & 0xff) << 24;
        System.out.println(accum);
        return Float.intBitsToFloat(accum);
    }

    protected void dengluBtn_Action() {

        alreadyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alreadyBtn.setClickable(false);
                if (ClickUtil.isFastClick(1000, v)) {
                    return;
                }
//                Log.e("dddddd","====="+ NumberBaseConversionUtil.SixToDecimalTen("9c20"));

//                String msg = "2e63766900000000d5c5020100000023008D0000000020008D000000005000990000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000000020008D0000010000014E2000002e646e0d";
//                String msg = "2e637669 0049 0000 7a04 0202 00 00 0020 008d 0000 00 0040 008d 000000 0080 008d 000000 0100 008d 000000 0200 008d 000000 0400 008d 000000 0800 008d 000000 1000008d 000000 2000 008d 000000 4000 008d 000001 0000 2e646e0d";
//                StringUtil.dealWithMsgReceive(msg);

//                  warning修改
//                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//                intent.putExtra("TYPE","[TYPE]-[C25]-[VERSION]-[20200717]");
//                startActivity(intent);
//                finish();
//                hideDialog();

                App.getContext().reinitSocket();
                App.getContext().getNettyClient().setListener(LoginActivity.this);
        /*        handler = new Handler();
                runnable5 = new Runnable() {
                    @Override
                    public void run() {
                        App.getContext().getProtocolServiceUtil().selectEquipmentNumbe();
                        handler.postDelayed(this, 20000);
                    }
                };
                handler.postDelayed(runnable5, 800);*/
                mDialog.setMsg("正在连接...");
                showDialog();
                if (!App.getContext().getNettyClient().getConnectStatus()) {
                    App.getContext().getNettyClient().connect();
                }
            }
        });
        manualBtn.setVisibility(View.INVISIBLE);
        manualBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.init(App.getContext());
                ToastUtils.show("暂未开放!");
//                ToastUtils.showToast(activity,"暂未开放!");
//                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//                startActivity(intent);
//                finish();
//                hideDialog();
            }
        });

    }

    protected void queryType() {
//        App.getContext().getHexadecimal().setQUERY(Constants.QUERYEnum.type);
    }

    @Override
    public void onMessageReaderTimeout() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                alreadyBtn.setClickable(true);
//                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//                intent.putExtra("TYPE","");
//                startActivity(intent);
//                finish();
//                hideDialog();
            }
        });
    }

    /*
      回调客户端接收的信息
     */
    @Override
    public void onMessageResponse(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("LoginActivity11111",msg);
                if (msg.contains("TYPE")) {

                }
            }
        });
    }

    //连接状态变化的时候 会走这
    @Override
    public void onServiceStatusConnectChanged(final int statusCode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialog.hide();
                if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {
                    Log.e(TAG, "STATUS_CONNECT_SUCCESS:");
                    if (App.getContext().getNettyClient().getConnectStatus()) {

                        Toast.makeText(LoginActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        // 查询设备type
//                        queryType();
                        hideDialog();
                        alreadyBtn.setClickable(true);
                        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//                        intent.putExtra("TYPE",msg);
                        startActivity(intent);
                        finish();
                      //  handler.removeCallbacks(runnable5);
                    }
                } else {
                    alreadyBtn.setClickable(true);
                    Toast.makeText(LoginActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "onServiceStatusConnectChanged:" + statusCode);
                    if (!App.getContext().getNettyClient().getConnectStatus()) {
//                        Toast.makeText(LoginActivity.this, "网路不好，正在重连", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }


    Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            int flags;
            int curApiVersion = Build.VERSION.SDK_INT;
            if (curApiVersion >= Build.VERSION_CODES.KITKAT) {
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE
                        | View.SYSTEM_UI_FLAG_FULLSCREEN;

            } else {
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }
            getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    };

    /**
     * 隐藏虚拟按键，并且设置成全屏
     */
    protected void hideBottomUIMenu() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBind){
            unbindService(sc);
        }
    }

    @Override
    protected void initImmersionBar() {
        ImmersionBar mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
        mImmersionBar.transparentBar();
    }

}
